package com.seed.core.builder.declare;

import cn.hutool.core.util.StrUtil;
import com.seed.core.column.Column;
import com.seed.core.enumeration.PropertyType;
import com.seed.core.pojo.seed.Relation;
import com.seed.core.pojo.seed.Seed;
import com.seed.core.query.pojo.Declared;
import com.seed.util.SeedKit;
import com.seed.util.StrKit;

import java.util.*;

public class DeclaredBuilder {
    protected final Seed seed; // 当前访问的模块
    protected final List<String> values; // 申明配置，形如：column1,cross.column2

    public DeclaredBuilder(Seed seed, List<String> values) {
        this.seed = seed;
        this.values = values;
    }

    public Map<String, Declared> build() {
        Map<String, Declared> ret = new LinkedHashMap<>();
        for(String declare: values) build(ret, seed, declare);

        return ret;
    }

    private void build(Map<String, Declared> parent, Seed seed, String declare) {
        declare = StrUtil.toUnderlineCase(declare);
        Map<String, Column> columns = seed.getColumns();
        if(declare.contains(".")) {
            String[] items = StrKit.cutInTwo(declare, '.', false);
            String cross = items[0];
            String subDeclare = items[1];
            Relation relation = SeedKit.getRelation(seed, cross);
            Declared declared = parent.get(cross);
            if(declared == null) declared = new Declared(relation);
            build(declared, relation.targetSeed(), subDeclare);
            parent.put(cross, declared);
        } else {
            if("".equals(declare)) {
                Declared declared = parent.get(declare);
                if(declared == null) parent.put(declare, new Declared(PropertyType.none));
            } else if("*".equals(declare)) {
                Declared declared = parent.get(declare);
                if(declared == null) parent.put(declare, new Declared(PropertyType.asterisk));
            } else {
                Column column = columns.get(declare);
                if(column == null) {
                    Relation relation = SeedKit.getRelation(seed, declare);
                    Declared declared = parent.get(declare);
                    if(declared == null) declared = new Declared(relation);
                    build(declared, relation.targetSeed(), "");
                    parent.put(declare, declared);
                } else {
                    Declared declared = parent.get(declare);
                    if(declared == null) parent.put(declare, new Declared(column));
                }
            }
        }
    }
}
